import { detailsId } from '@/api/system/user';
import { notify } from '@/utils/element';
import { ref, unref, reactive , toRefs , onMounted, nextTick } from 'vue';
import type { Ref } from 'vue';

interface Params {
    disableMounted?: boolean | Ref;
    mustQuery?: any;    //查询条件，使用reactive创建的响应式变量，方便后期更新
    getPageList: Function;  //查询列表的api方法
    deleteById?: Function;   //删除列表的api方法
}
/**
 * 针对分页列表组件实现逻辑
 */
function useTablePage<T = any, Q = any>(params: Params, emit?: Function, props?: any) {

    const tableListRef = ref();

    const editRef = ref();

    const state = reactive({
      loading: false,
      page: {
        pageNum: 1,
    pageSize: 20,
    total: 0,
      } as PageType,
      query: {} as Q,
      tableList: [] as T [],
    });

    onMounted(() => {
        //禁用首次加载，方便组件中其他位置触发加载列表
        if(unref(params.disableMounted)) return;
        queryData();
    });

    function queryData() {
        return new Promise((resolve, reject) => {
            state.loading = true;
            const { pageNum, pageSize } = state.page;
            //合并必须传递的查询条件
            const query = params.mustQuery ? Object.assign({}, state.query, params.mustQuery) : state.query;
            params.getPageList(query, pageNum, pageSize).then((resp: any) => {
                state.loading = false;
                const {total, data} = resp;

                state.page.total = total;
                state.tableList = data;
                console.log('state.tableList', state.tableList)
                resolve(resp);
            }).catch((error: Error) => {
                reject(error);
            }).finally(() => {
                state.loading = false;
            });
        });
    }

    //点击查询
    function handleQuery() {
        //将页码设置为第一页
        state.page.pageNum = 1;
        queryData();
    }

    //点击删除
    async function handleDelete(id: string) {
        //console.log('handleDelete', id);
        try {
            state.loading = true;
            if(params.deleteById) await params.deleteById(id);
            notify('删除成功！',{type: 'success'});
            queryData();
        } catch (error) {
        } finally {
            state.loading = false;
        }
    }

    function handleAdd(parentId?: string) {
        //console.log('handleAdd');
        editRef.value?.open('add', '新增', parentId);
    }

    async function handleEdit(row: T & {userId: string}) {
        const {data} = await detailsId(row.userId);
        editRef.value?.open('edit','修改',data);
    }

    return {
        tableListRef,
        editRef,
        ...toRefs(state),
        queryData,
        handleQuery,
        handleDelete,
        handleEdit,
        handleAdd,
    }
}

export default useTablePage;
export { useTablePage };
